package co.mobiless.noterecorder.activities;

import java.util.ArrayList;
import java.util.ListIterator;

import co.mobiless.noterecorder.AudioRecordTest;
import co.mobiless.noterecorder.Grabacion;
import co.mobiless.noterecorder.ImageSimpleCursorAdapter;
import co.mobiless.noterecorder.R;
import co.mobiless.noterecorder.StorageData;
import co.mobiless.noterecorder.fingerPaint;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import co.mobiless.noterecorder.Nota;

public class VerGrabacion extends Activity {
	private Chronometer chrono;
	private View fv;
	private ListView lv;
	private ImageButton rec;
	private TextView txtAdd;
	private Grabacion recObj;
	private Nota noteObj = new Nota();
	private AudioRecordTest aud= new AudioRecordTest(this);
	private StorageData db;
	private StorageData sd;
	private Cursor mNotasCursor;
	private String idGrab;
	private String idNota;
	private Boolean playing;
	private Boolean pausing;
	private long timePaused;
	private ArrayList<Nota> Notes;
	//TODO: mejorar barra superior y boton para colapsar lista
	//TODO: Manejo de estado del fingerpaint
	//TODO: Confirmar qeue se haya grabado la nota Cuando se agregan notas, actualizar listado
	//TODO: Controlar el no cruce de notas
	@Override
	 public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ver_grabacion);
		WindowManager w = getWindowManager();
        Display d = w.getDefaultDisplay();
		chrono=(Chronometer)findViewById(R.id.cronometro_play);
		lv = (ListView) findViewById(R.id.imageList);
		 fv = (View) findViewById(R.id.fingerPaint_play);
        ((fingerPaint) fv).setCanvas(d.getWidth(),d.getHeight(), chrono, noteObj );
        txtAdd = (TextView)findViewById(R.id.txtAdd);
		playing = false;
		pausing = false;
		db = new StorageData(this);
		sd = new StorageData(this);
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		idGrab = extras.getString("idGrabacion");
		if(extras.containsKey("idNota")){
			idNota = extras.getString("idNota");
		}
		recObj = db.fetcgGrabacionObj(Long.parseLong(idGrab));
        db.open();
        fillData(idGrab);
        Notes = sd.fetcallNotasObj(Integer.parseInt(idGrab));
        ((TextView)findViewById(R.id.title_rec_play)).setText(recObj.getTitulo());
        
        lv.setClickable(true); 
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
         
          public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {  
        	if(playing){
	        	ImageSimpleCursorAdapter adapter = (ImageSimpleCursorAdapter) parent.getAdapter(); 
	        	Nota selectedNote= adapter.getItem(position);
	        	setCurrentNote(selectedNote);
        	}
          }

		
        }); 
        
        chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener(){    
   	     
        	public void onChronometerTick(Chronometer chronometer) {      
        		getBitMapOnTime();
        		}

			
        } );
        
       
        
        rec = (ImageButton) findViewById(R.id.play);
        rec.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(playing){
					stopPlay(rec);
				}else
				{
					startPlay(rec);			        					
				}
			}

			
		});
        
        final ImageButton pausa = (ImageButton) findViewById(R.id.pausa_play);
        pausa.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(playing){
					if(pausing){
						resumePlay(pausa);
					}else
					{
						pausePlay(pausa);			        					
					}
				}
			}

			
		});
        final ImageButton del = (ImageButton) findViewById(R.id.clearScreen_play);
        del.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				((fingerPaint) fv).clearCanvas();
			}
		});
        final ImageButton save = (ImageButton) findViewById(R.id.save_note_play);
        save.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(playing){
					noteObj.setId(sd.getNoteNewId(Integer.parseInt(idGrab)));
					noteObj.setId_grabacion(Integer.parseInt(idGrab));
					noteObj.setTiempoFin(chrono.getText().toString());
					noteObj.setUbicacionImagen(recObj.getUbicacionAudio());
					noteObj.setNombre("Nota" + noteObj.getId().toString());
					noteObj.setNombreArchivoImagen(noteObj.getNombre() + ".png");
					sd.saveNote2(fv, noteObj );
					fillData(idGrab);
				}
				((fingerPaint) fv).clearCanvas();
				
				//noteNum++;
				//TextView tv = (TextView)findViewById(R.id.no_nota);
		        //tv.setText("Nota " + noteNum.toString());*/
			}
		});
        final Button btn = (Button) findViewById(R.id.hidelist);
        btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(lv.getVisibility() == View.GONE){
					lv.setVisibility(View.VISIBLE);
				}else{
					lv.setVisibility(View.GONE);
				}
			}
		});
       
	 }
	private void fillData(String idGrab) {
        // Get all of the records from the database and create the item list
    	Integer idGrabacion=new Integer(idGrab);
    	mNotasCursor = db.fetchAllNotas("",idGrabacion);
        startManagingCursor(mNotasCursor);
        
        String[] from = new String[] { StorageData.KEY_ROW_NAME_NOTE };
        int[] to = new int[] { R.id.nombreNota };
        
        // Now create an array adapter and set it to display using our row
        
        ImageSimpleCursorAdapter records = new ImageSimpleCursorAdapter(this, R.layout.fila_notaimagen, mNotasCursor, from, to);
        lv.setAdapter(records);
        Notes = null;
        Notes = sd.fetcallNotasObj(Integer.parseInt(idGrab));
       
    } 
	private void startPlay(final ImageButton rec) {
			playing = true;
			rec.setImageResource(R.drawable.stop_icon);
			aud.startPlaying(recObj.getUbicacionAudio() + "/" + recObj.getNombreArchivoAudio());
			aud.mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
	        	public void onCompletion(MediaPlayer mp) { 
	        		Log.d("PlayBack","Fin reproduccion");
	        		Toast.makeText(VerGrabacion.this, "Fin reproduccion" , Toast.LENGTH_LONG).show();
	        		stopPlay(rec);
	        	}
	        });
			chrono.setBase(SystemClock.elapsedRealtime());
			chrono.start();
	}
	private void stopPlay(final ImageButton rec) {
		rec.setImageResource(R.drawable.play_icon);
		playing=false;
		//aud.cancel(true);
		aud.stopPlaying();
		chrono.stop();
		timePaused=0;
	}
	private void pausePlay(final ImageButton rec) {
		pausing = true;
		aud.pausePlaying();
		//TODO: crear metodo para convertir milisegundostotext
		String chronoText = chrono.getText().toString(); 
        String array[] = chronoText.split(":"); 
        if (array.length == 2) { 
        	timePaused = Integer.parseInt(array[0]) * 60 *1000 + Integer.parseInt(array[1]) * 1000;
         } else if (array.length == 3) { 
        	 timePaused = 	Integer.parseInt(array[0]) * 60 * 60* 1000 + Integer.parseInt(array[1]) * 60 * 1000
        	 + Integer.parseInt(array[2]) * 1000;
         } 

		chrono.stop();
	}
	private void resumePlay(final ImageButton rec) {
		pausing=false;
		aud.resumePlaying();
		chrono.setBase(SystemClock.elapsedRealtime() - timePaused);
		chrono.start();
}
	private void getBitMapOnTime() {
		Long myElapsedMillis = SystemClock.elapsedRealtime() - chrono.getBase();   
		ListIterator itr = Notes.listIterator();
		while(itr.hasNext()) {
			Nota note=(Nota) itr.next();
			Log.d("timepos",note.getTiempoInicio() + " ___ " + myElapsedMillis.toString());
			Long tiempo= Long.parseLong(note.getTiempoInicio());
		    if(tiempo >= (myElapsedMillis-1000) && tiempo <= (myElapsedMillis+1000)	){
		    	//Log.d("timepos",note.getTiempoInicio() + " ___ " + myElapsedMillis.toString());
		    	//Toast.makeText(VerGrabacion.this, note.getTextoAdicional() , Toast.LENGTH_LONG).show();
		    	txtAdd.setText(note.getTextoAdicional());
		    	Bitmap b = new BitmapFactory().decodeFile(note.getUbicacionImagen()+"/"+note.getNombreArchivoImagen());
	            ((fingerPaint) fv).setBitmap(b);
		    }
		}
	}
	private void setCurrentNote(Nota noteObj) {
		Long mTime = Long.parseLong(noteObj.getTiempoInicio());
		aud.goToMsec(mTime<=500?mTime:mTime-500);
		timePaused = mTime<=500?mTime:mTime-500;
		//Toast.makeText(VerGrabacion.this, adapter.getItem(position).getTextoAdicional() , (int)(Long.parseLong(adapter.getItem(position).getTiempoInicio())-Long.parseLong(adapter.getItem(position).getTiempoFin()))).show();
		chrono.setBase(SystemClock.elapsedRealtime() - timePaused);
		//Bitmap b = new BitmapFactory().decodeFile(noteObj.getUbicacionImagen()+"/"+noteObj.getNombreArchivoImagen());
		//((fingerPaint) fv).setBitmap(b);
	} 
	public void onPause()
	  {
	    super.onPause();
	  }
	public void onResume(){
		super.onResume();
		 if(idNota != null){
	        	startPlay(rec);
	        	setCurrentNote(sd.fetcNotaObj(Long.parseLong(idNota)));
	        }
	}
}
